package ar.com.utn.openqsb.lip.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author rvega
 * 
 */
public class LIPManager
{

    private static LIPManager instance;

    Map<String, Exercise> opened = new HashMap<String, Exercise>();

    static
    {
        instance = new LIPManager();
    }

    /**
     * Get an instance of the manager.
     */
    public static LIPManager getInstance()
    {
        return instance;
    }

    /**
     * Create a new exercise.
     * 
     * @param exercise
     *            the exercise to add.
     */
    public void create(final Exercise exercise) throws LIPException
    {
        validate(exercise);
        opened.put(exercise.getName(), exercise);
    }

    public Exercise get(final String exerciseId)
    {
        return opened.get(exerciseId);
    }

    public void remove(final String exerciseId)
    {
        opened.remove(exerciseId);
    }

    public SimplexResult solve(final Exercise exercise)
    {
        SimplexSolver solver = new SimplexSolver(exercise.getModel());
        try
        {
            return solver.solve();
        } catch (UnboundedSolutionException e)
        {
            e.printStackTrace();
        } catch (NoFeasibleSolutionException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    private void validate(final Exercise exercise) throws LIPException
    {
        if (exercise.getName().isEmpty())
        {
            throw new LIPException("An exercise must have a name.");
        }
        if (opened.containsKey(exercise.getName()))
        {
            throw new LIPException("An exercise with this name already exist.");
        }
        if (exercise.getNumVars() <= 0)
        {
            throw new LIPException("The number of variables should be greater than 0.");
        }
        if (exercise.getNumConstraints() <= 0)
        {
            throw new LIPException("The number of constraints should be greater than 0.");
        }
    }

    public void save(final String exerciseId, File file) throws LIPException
    {
        try
        {
            FileWriter writer = new FileWriter(file);
            writer.write(opened.get(exerciseId).toString());
            writer.close();
        } catch (IOException e)
        {
            throw new LIPException("Error trying to save exercise " + exerciseId + " on the file " + file.getAbsolutePath() + ". " + e.getMessage(), e);
        }
    }

    public Exercise open(File file) throws LIPException
    {
        try
        {
            String fileContent = loadFile(file.getAbsolutePath());
            Exercise exercise = new Exercise(fileContent);
            create(exercise);
            return exercise;
        } catch (Throwable t)
        {
            throw new LIPException("Error trying to open exercise from file " + file.getAbsolutePath() + ". " + t.getMessage(), t);
        }
    }

    private String loadFile(String filePath) throws IOException
    {
        StringBuilder result = new StringBuilder();
        File in = new File(filePath);
        BufferedReader reader = new BufferedReader(new FileReader(in));
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            result.append(line).append("\n");
        }
        return result.toString();
    }
}
